package com.gene.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gene.pojo.UpmsUser;
import com.gene.utils.CodeValue;
import com.gene.utils.JWT;
import com.gene.utils.MsgValue;
import com.gene.utils.ResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor{
	@Autowired
	private RedisTemplate<String, String> template;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
		String url = request.getRequestURI();
		System.out.println(url);
		if(url.equals("/gene-safe/")){
			response.sendRedirect("/gene-safe/index");
			return false;
		}
		if(url.equals("/gene-safe/index")||url.equals("/gene-safe/WEB-INF/index.html")){
			return  true;
		}
		String token = request.getHeader("Authorization");
		System.out.println(token);
		ResultData data=new ResultData();
		if(null!=token  && !"".equals(token)){
			UpmsUser login = JWT.unsign(token, UpmsUser.class);
			String s = template.opsForValue().get(login.getUserId() + login.getUsername());
			if(s.equals(token)){
				//token 一致

				return true;
			}else {
				//不一致或过期
				data.setErrorCode(CodeValue.TOKEN_ISNULL);
				data.setMsg(MsgValue.TOKEN_ISNULL);
				response.getWriter().write(data.toString());
				return false;
			}

		}
		data.setErrorCode(CodeValue.TOKEN_ISNULL);
		data.setMsg(MsgValue.TOKEN_ISNULL);
		response.getWriter().write(data.toString());
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

}
